<?php

namespace Wechat\Controller;

class BookingController extends CommonController {


    public function index() {

        $id = $_REQUEST["id"];

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("Index/index"));
        }

        $category = D("Category")->queryById($product["category_id"]);

        if($category["is_finished"] != C("DEFAULT_YN.NO")) {
            $this->redirect(U("Index/index"));
        }

        $this->assign("appId", C("appid"));
        $this->assign("config", $this->signature());
        $this->assign("product", $product);
        $this->assign("category", $category);
        $this->display("index");

    }

    public function booking() {

        $productId = I("post.productId");

        $product = D("Product")->queryById($productId);

        $data["code"] = 200;

        if(isNullOrEmpty($product)) {
            $data["code"] = -1;
            $data["msg"] = "商品不存在";
            echo json_encode($data);
            exit();
        }

        $category = D("Category")->queryById($product["category_id"]);

        if($category["is_finished"] != C("DEFAULT_YN.NO")) {
            $data["code"] = -2;
            $data["msg"] = "商品为成品，请直接购买";
            echo json_encode($data);
            exit();
        }

        //判断当天是否重复预约
        $customerMap["customer_id"] = $this->customer["customer_id"];
        $customerMap["idcard_number"] = I("post.idcardNumber");
        $customerMap["product_id"] = $productId;
        $customerMap["booking_time"] = I("post.day");
        $customerMap["booking_type"] = I("post.bookingType");
        $customerMap["status"] = 1;
        $booking = D("Booking")->where($customerMap)->find();
        if(!isNullOrEmpty($booking)){
            $data["code"] = -6;
            if($customerMap["booking_type"] == C("BOOKING_TYPE.SHOP"))
                $data["msg"] = "对不起，".$customerMap["booking_time"]."日您已经预约到我方监测点取型评估";
            else
                $data["msg"] = "对不起，".$customerMap["booking_time"]."日您已经预约上门服务";
            echo json_encode($data);
            exit();
        }

        $logMap["product_id"] = $productId;
        $logMap["day"] = I("post.day");
        $bookingLog = D("BookingLog")->where($logMap)->find();

        if($bookingLog["status"] == -1) {
            $data["code"] = -5;
            $data["msg"] = "对不起，该日已被约满。";
            echo json_encode($data);
            exit();
        }

        $bookingType = I("post.bookingType");

        if($bookingType == C("BOOKING_TYPE.SHOP")) {

            $bookingData["booking_time"] = I("post.day");
            $bookingData["create_time"] = getCurrentDate();
            $bookingData["customer_id"] = $this->customer["customer_id"];
            $bookingData["booking_type"] = $bookingType;
            $bookingData["status"] = C("BOOKING_STATUS.WAITING_SERVICE");
            $bookingData["name"] = I("post.name");
            $bookingData["sex"] = I("post.sex");
            $bookingData["age"] = I("post.age");
            $bookingData["mobile"] = I("post.mobile");
            $bookingData["idcard_number"] = I("post.idcardNumber");
            //$bookingData["address"] = I("post.address");
            $bookingData["price"] = 0;
            $bookingData["product_id"] = $productId;
            $bookingData["category_id"] = $product["category_id"];
            $bookingData["location_type"] = I("post.shopId");
            $bookingData["pay_id"] = 0;
            $bookingData["shop_id"] = I("post.shopId");
            $bookingData["doctor_name"] = I("post.doctorName");
            $bookingData["hospital_name"] = I("post.hospitalName");

            $bookingId = D("Booking")->add($bookingData);

            if(isNullOrEmpty($bookingLog)) {
                $logData["product_id"] = $productId;
                $logData["day"] = I("post.day");
                $logData["status"] = 1;
                $logData["number"] = 1;
                $logData["create_time"] = getCurrentDate();
                $logData["shop_id"] = I("post.shopId");

                D("BookingLog")->add($logData);
            } else {

                if($bookingLog["number"] >= 3) {
                    $bookingLog["status"] = -1;
                }
                $bookingLog["number"] = $bookingLog["number"] + 1;

                D("BookingLog")->updateInfo($bookingLog);

            }

            $data["code"] = 999;
            $data["msg"] = "预约成功";

            //推送预约信息到管理员
            $bookingSuccessData["title"] = $bookingData["name"]
                ."刚刚预约了".$bookingData["booking_time"]."来公司临床部进行测量检查，相关产品是".$product["product_name"];
            $bookingSuccessData["orderNumber"] = $bookingId;
            $bookingSuccessData["serviceName"] = $product["product_name"];
            $bookingSuccessData["price"] = $product["price"];
            $bookingSuccessData["remark"] = "希卫康系统自动推送";
            bookingShopNotify($bookingSuccessData);

            echo json_encode($data);
            exit();

        } else if($bookingType == C("BOOKING_TYPE.HOME")) {

            $rule = D("Rule")->queryById(I("post.ruleId"));

            if(isNullOrEmpty($rule)) {
                $data["code"] = -4;
                $data["msg"] = "价格类型不存在";
                echo json_encode($data);
                exit();
            }

            $payId = D('Pay')->add(array(
                'out_trade_no' => time() . rand(0, 999),
                'money' => $rule['price'],
                'status' => 0,
                'callback' => "",
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => 1
            ));

            $bookingData["booking_time"] = I("post.day");
            $bookingData["create_time"] = getCurrentDate();
            $bookingData["customer_id"] = $this->customer["customer_id"];
            $bookingData["booking_type"] = $bookingType;
            $bookingData["status"] = C("BOOKING_STATUS.WAITING_PAY");
            $bookingData["name"] = I("post.name");
            $bookingData["sex"] = I("post.sex");
            $bookingData["age"] = I("post.age");
            $bookingData["mobile"] = I("post.mobile");
            $bookingData["idcard_number"] = I("post.idcardNumber");
            $bookingData["address"] = I("post.address");
            $bookingData["price"] = $rule["price"];
            $bookingData["product_id"] = $productId;
            $bookingData["category_id"] = $product["category_id"];
            $bookingData["location_type"] = I("post.shopId");
            $bookingData["pay_id"] = $payId;
            $bookingData["shop_id"] = I("post.shopId");
            $bookingData["doctor_name"] = I("post.doctorName");
            $bookingData["hospital_name"] = I("post.hospitalName");

            D("Booking")->add($bookingData);

        } else {
            $data["code"] = -3;
            $data["msg"] = "预约类型不存在";
            echo json_encode($data);
            exit();
        }

        $pay = D("Pay")->queryById($payId);

        //支付相关
        $arr = array(
            'appid' => C('appid'),
            'mch_id' => C('mch_id'),
            'nonce_str' => $this->createNoncestr(),
            //'sign' => '',	//签名
            'body' => "希卫康产品预约",
            'out_trade_no' => $pay['out_trade_no'], //订单号
            'total_fee' => $pay['money'] * 100, //金额
            'spbill_create_ip' => get_client_ip(),
            'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/handlePayBooking', //通知地址
            'trade_type' => 'JSAPI',
            'openid' => $this->customer['openid'],
        );

        $arr['sign'] = $this->getSign($arr);  //签名

        $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

        $arr2 = $this->xmlToArray($post);

        $jsApiObj["appId"] = C('appid');
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);

        $data["webarr"] = $jsApiObj;

        echo json_encode($data);

    }

    public function getDayLogByCondition($productId, $shopId) {

        $fromDay = date("Y-m-d");
        $toDay = date("Y-m-d", strtotime("+16 days"));

        $dayArray = array();

        $map["day"] = array('between',array($fromDay, $toDay));
        $map["product_id"] = $productId;
        $map["shop_id"] = $shopId;
        
        $logList = D("BookingLog")->where($map)->order("day asc")->select();

        for($i=0; $i<16; $i++) {

            $data["day"] = date("Y-m-d", strtotime("+$i days"));
            $data["status"] = 1;
            foreach ($logList as $log) {
                if($log["day"] == $data["day"]) {
                    $data["status"] = $log["status"];
                    break;
                }
            }

            array_push($dayArray, $data);

        }

        return $dayArray;

    }

    public function shopList() {

        $productId = I("post.productId");

        $list = D("Shop")->select();
        $index = 0;
        foreach ($list as &$item) {
            $item["index"] = $index++;
        }

        $data["list"] = $list;
        $data["day_list"] =
            $this->getDayLogByCondition($productId, $list[0]["shop_id"]);

        echo json_encode($data);
    }

}